package gulimall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import gulimall.entity.Brand;
import gulimall.entity.CategoryBrandRelation;
import gulimall.mapper.BrandMapper;
import gulimall.service.CategoryBrandRelationService;
import gulimall.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gulimall.utils.PageUtils;
import gulimall.utils.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 品牌 服务实现类
 * </p>
 *
 * @author HLF
 * @since 2022-04-23
 */
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    private BrandMapper brandMapper;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * 多字段模糊匹配
         * 查询条件：brandId = key or name like '%key%' or descript like '%key%'
         */
        String key = (String) params.get("key");
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Brand::getBrandId, key)
                .or().like(Brand::getName, key)
                .or().like(Brand::getDescript, key);

        IPage<Brand> page = this.page(
                new Query<Brand>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 不仅要更改pms_brand中的内容，还要改变引用pms_brand中字段的其他表
     * 1.改变pms_brand
     * 2.改变pms_category_brand_relation
     * 3.TODO 更新其他关联表
     * @param brand
     */
    @Override
    @Transactional
    public void updateDetail(Brand brand) {
        //1.改变pms_brand
        brandMapper.updateById(brand);

        if (StringUtils.isNotBlank(brand.getName())) {
            //2.同步更新其他关联表中的数据
            //更新pms_category_brand_relation中的brandId，brandName
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());

            //TODO 更新其他关联表
        }
    }
}
